<?php

namespace App\Http\Controllers\Admin;
use App\Models\Kfdisease;
use App\Models\Kftags;
use App\Models\Kfdepartment;
use App\Models\DiancanUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Admin\Traits\MessageTraits;
use App\Filters\DepartmentFilters;


class DepartmentController extends Controller
{
    public function index(DepartmentFilters $filters,Kfdepartment $department)
    {
        $dep =  $department->Filter($filters)->paginate(20);
        return view('admin.department.index',compact('dep'));
    }


    public function create()
    {
        $tag = Kftags::get();
        return view('admin.department.create',compact('tag'));
    }

    public function store(Request $request)
    {
        $data = $request->except('_token','tags','pic');
        if ($request->hasFile('pic')) {           
            $filename = date('YmdHis').'.'.$request->pic->extension();
            $request->pic->storeAs('public/pic',$filename);            
            $data['pic']  = '/storage/pic/'.$filename; 
        } 
        Kfdepartment::create($data);
        Kftags::create($request->tags);

        return redirect('zadmin/department');
    }

    public function edit(Kfdepartment $department)
    {
        $tag = Kftags::get();
        $tags_id = $department->tags->pluck('id')->all();
        return view('admin.department.edit',compact('department','tag','tags_id'));
    }


    public function update(Request $request,Kfdepartment $department)
    {   
       // dd($department);
        $data = $request->except('_token','method','tags','pic');
        if ($request->hasFile('pic')) {           
            $filename = date('YmdHis').'.'.$request->pic->extension();
            $request->pic->storeAs('public/pic',$filename);            
            $data['pic']  = '/storage/pic/'.$filename; 
        } 
        $department->update($data);
        $department->tags()->sync($request->tags);
        
        return redirect('zadmin/department');

    }

    public function delete(Request $request,Kfdepartment $department)
    {
        DB::table('kf_diseases_department')->where('department_id',$request->id)->delete();
        $department->find($request->id)->delete();

        return back();


    }
}
